/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.ecommerce.model.dao;

import br.com.ecommerce.model.Cliente;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.Transaction;

/**
 *
 * @author Admin
 */
public class ClienteDAO {

    private Session session = null;
    private Transaction transaction = null;

    public void cadastrarCliente(Cliente obj) {
        Integer id = (Integer)session.save(obj);
        obj.setCodCliente(id);
    }

    public void atualizarCliente(Cliente obj) {
        session.update(obj);
    }

    public void excluirCliente(Cliente obj) {
        session.delete(obj);
    }

    public Cliente obterCliente(int codCliente) {
        Cliente obj = (Cliente) session.get(Cliente.class, codCliente);
        return obj;
    }

    public Cliente obterCliente(Cliente cliente) {
        Query query = session.createQuery("from Cliente as c " +
                "where c.loginCliente = \'" + cliente.getLoginCliente() + " \' " +
                "and c.senhaCliente = \'" + cliente.getSenhaCliente() + "\'");
        List<Cliente> clientes = query.list();
        
        Cliente obj;
        if (clientes.isEmpty())
            obj = null;
        else
            obj = clientes.get(0);
        
        return obj;
    }

    @SuppressWarnings("unchecked") //warning query.list()
    public List<Cliente> listarClientes() {
        Query query = session.createQuery("from Cliente");
        List<Cliente> pessoas = query.list();
        return pessoas;
    }

    @SuppressWarnings("unchecked") //warning query.list()
    public List<Cliente> buscarCliente(Cliente obj) {
        Query query = session.createQuery("from Cliente as p " +
            "where p.nomeCliente like \'%" + obj.getNomeCliente() + "%\'");
        List<Cliente> clientes = query.list();
        return clientes;
    }

    //begin
    public void beginHibernate() {
        try {
            session = HibernateUtil.getSession();
            transaction = session.beginTransaction();
        } catch (HibernateException e) {
            System.out.println("\nErro Begin Hibernate.\n\n");
            e.printStackTrace();
        }
    }
    
    //commit
    public void commitTransaction() {
        try {
            transaction.commit();
        } catch (HibernateException e) {
            System.out.println("\nError Commit Transaction.\n\n");
            e.printStackTrace();
        }
    }

    //close
    public void closeSession() {
        try {
            session.close();
        } catch (HibernateException e) {
            System.out.println("\nError Close Session.\n\n");
            e.printStackTrace();
        }
    }
    }
